package org.example.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

// 单例模式的 HTTP 请求工具类
public class HttpUtils {
    // 单例实例
    private static final HttpUtils INSTANCE = new HttpUtils();
    // Apache HttpClient 实例
    private final HttpClient httpClient;

    // 私有构造函数，防止外部实例化
    private HttpUtils() {
        this.httpClient = HttpClients.createDefault();
    }

    // 获取单例实例的方法
    public static HttpUtils getInstance() {
        return INSTANCE;
    }

    // 发送 GET 请求
    public String sendGetRequest(String url, Map<String, String> headers) throws IOException {
        // 创建 HttpGet 请求对象
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 执行请求并获取响应
        HttpResponse response = httpClient.execute(httpGet);
        // 获取响应实体
        HttpEntity entity = response.getEntity();
        // 将响应实体转换为字符串
        return entity != null ? EntityUtils.toString(entity) : null;
    }

    // 发送 POST 请求
    public String sendPostRequest(String url, String body, Map<String, String> headers) throws IOException {
        // 创建 HttpPost 请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置请求体
        if (body != null) {
            StringEntity entity = new StringEntity(body);
            httpPost.setEntity(entity);
        }
        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 执行请求并获取响应
        HttpResponse response = httpClient.execute(httpPost);
        // 获取响应实体
        HttpEntity responseEntity = response.getEntity();
        // 将响应实体转换为字符串
        return responseEntity != null ? EntityUtils.toString(responseEntity) : null;
    }
}